package com.example.hbuildble

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.OpenableColumns
import android.text.method.ScrollingMovementMethod
import android.view.MotionEvent
import android.view.ViewGroup
import androidx.activity.OnBackPressedCallback
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.updateLayoutParams
import androidx.recyclerview.widget.GridLayoutManager
import com.example.hbuildble.databinding.ActivityTestingBinding
import com.google.gson.Gson
import com.longtxt.powerband.PbManager
import com.longtxt.powerband.models.BandAlarmData
import com.longtxt.powerband.models.BandHeartSettingData
import com.longtxt.powerband.models.BandTimeModel
import com.longtxt.powerband.models.BandUserInfo
import com.longtxt.powerband.models.BandWeatherData
import com.longtxt.powerband.models.BaseResponse
import com.longtxt.powerband.models.CustomThemeData
import com.longtxt.powerband.models.WatchNotifyData
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import java.io.File
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale

class TestingActivity : AppCompatActivity() {
    private lateinit var binding: ActivityTestingBinding
    private val fullFmt = SimpleDateFormat("HH:mm:ss.SSS", Locale.getDefault())

    private lateinit var alertDialog: AlertDialog

    private var themeFileName = ""
    private var cameraStatus = false
    private var otaFileP = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivityTestingBinding.inflate(layoutInflater)
        setContentView(binding.root)

        ViewCompat.setOnApplyWindowInsetsListener(binding.toolbar) { v, windowInsets ->
            val insets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.updateLayoutParams<ViewGroup.MarginLayoutParams> {
                topMargin = insets.top
            }
            WindowInsetsCompat.CONSUMED
        }
        setSupportActionBar(binding.toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        initUI()
    }

    private fun initUI() {
        onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                showInfoDialog("退出", "确定要退出吗？"){
                    showLoadingDialog()
                    PbManager.disconnect {
                        dismissLoadingDialog()
                        finish()
                    }

                }
            }
        })
        alertDialog = AlertDialog.Builder(this).setView(R.layout.dialog_loading).create()
        binding.logView.apply {
            movementMethod = ScrollingMovementMethod.getInstance()
            setOnTouchListener { view, motionEvent ->
                view.parent.requestDisallowInterceptTouchEvent(true)
                when (motionEvent.action and MotionEvent.ACTION_MASK) {
                    MotionEvent.ACTION_UP -> view.parent.requestDisallowInterceptTouchEvent(false)
                }
                performClick()
            }
        }
        binding.btnListView.layoutManager = GridLayoutManager(this, 3)
        binding.btnListView.adapter = CommandBtnAdapter(
            listOf(
                "SDK版本",
                "基础配置",
                "功能支持",
                "手环版本",
                "用户信息",
                "运动数据监听",
                "同步运动数据",
                "睡眠数据监听",
                "获取睡眠数据",
                "获取SOC",
                "开始体检",
                "同步手机系统",
                "同步时间和语言",
                "查找手环",
                "同步天气",
                "设置用户信息",
                "设置防丢",
                "开启手势",
                "设置亮屏",
                "发送表盘",
                "发送表盘背景",
                "选择OTA文件",
                "初始化OTA",
                "测试OTA",
                "释放OTA",
                "切换摇一摇状态",
                "监听摇一摇",
                "发送普通消息",
                "发送来电消息",
                "接挂电话监听",
                "清空来电通知",
                "监听找手机",
                "监听打开拍照",
                "设置闹钟",
                "设置心率参数",
                "是否初始化",
                "是否连接中",
                "断开链接",
                "恢复出厂"
            ),
            block = handleClickAction
        )
    }

    private var sleepDay = 0

    private val handleClickAction: (Int, String) -> Unit = { position, title ->
        logInfo("Click $title")
        when (title) {
            "基础配置" -> getBasicConfig()
            "功能支持" -> getSupportedFeatures()
            "手环版本" -> {
                PbManager.getBandVersion {
                    logInfo("band version: $it")
                }
            }
            "用户信息" -> getUserInfo()
            "运动数据监听" -> {
                PbManager.addSportDataListener {
                    logInfo("sport data: $it")
                }
            }

            "同步运动数据" -> {
                PbManager.getSportData(0)
            }
            "睡眠数据监听" -> {
                PbManager.addSleepDataListener {
                    logInfo("睡眠数据: $it")
                }
            }

            "获取睡眠数据" -> {
                logInfo("开始获取第 $sleepDay 天数据")
                PbManager.getSleepDetail(sleepDay)
            }
            "获取SOC" -> {
                PbManager.getBatterySoc {
                    logInfo("当前SOC: $it")
                }
            }
            "开始体检" -> {
                PbManager.startHealthExamine {
                    logInfo("startExamine: $it")
                }
            }

            "同步手机系统" -> {
                PbManager.setOSPlatform(0) {
                    logInfo("syncOsPlatform: $it")
                }
            }

            "同步时间和语言" -> {
                var lanCode = 0
                if (Locale.getDefault().language == "zh") {
                    lanCode = when (Locale.getDefault().toLanguageTag()) {
                        "zh-Hant-TW" -> 2
                        else -> 1
                    }
                }

                val calendar = Calendar.getInstance(Locale.getDefault())
                val year = (calendar.get(Calendar.YEAR) % 2000)
                val mon = (calendar.get(Calendar.MONTH) + 1)
                val day = calendar.get(Calendar.DAY_OF_MONTH)
                val hour = calendar.get(Calendar.HOUR_OF_DAY)
                val min = calendar.get(Calendar.MINUTE)
                val second = calendar.get(Calendar.SECOND)
                val bandTimeModel = BandTimeModel(
                    year,
                    mon,
                    day,
                    hour,
                    min,
                    second,
                    lanCode
                )
                PbManager.syncTimeAndLanguage(Gson().toJson(bandTimeModel)) {
                    logInfo("syncLanguage: $it")
                }
            }

            "查找手环" -> {
                PbManager.findBand {
                    logInfo("findBand: $it")
                }
            }

            "同步天气" -> {
                val bandWeatherData = BandWeatherData(
                    1,  // 天气类型
                    20, // 温度
                    10, // 最低温度
                    30  // 最高温度
                )
                PbManager.syncWeatherToBand(Gson().toJson(bandWeatherData)) {
                    logInfo("syncWeather: $it")
                }
            }

            "设置用户信息" -> {
                val bandUserInfo = BandUserInfo(
                    0,
                    18,
                    180,
                    70,
                    7000,
                    0
                )
                PbManager.setUserInfo(Gson().toJson(bandUserInfo)) {
                    logInfo("setUserInfo: $it")
                }
            }

            "设置防丢" -> {
                PbManager.setAntiLost(true) {
                    logInfo("setAntiLost: $it")
                }
            }

            "开启手势" -> {
                PbManager.setGestureLightUp(true) {
                    logInfo("setGesture: $it")
                }
            }

            "设置亮屏" -> {
                PbManager.setScreenSaver(6) {
                    logInfo("setScreenLight: $it")
                }
            }

            "发送表盘" -> {
                testThemeFeature()
            }
            "初始化OTA" -> {
                PbManager.initOtaModule {
                    logInfo("initOtaModule: $it")
                    val resp = Gson().fromJson<BaseResponse<String>>(it, BaseResponse::class.java)
                    if (resp.code == -1 ){
                        showInfoDialog("提示", "设备需要强制升级，请选择固件进行升级"){

                        }
                    }
                }
            }
            "测试OTA" -> {
                testOtaFeature()
            }
            "选择OTA文件" -> {
                openFilePicker()
            }
            "释放OTA" -> {
                PbManager.deInitOtaModule {
                    logInfo(it)
                }
            }
            "发送表盘背景" -> testCustomBgFeature()
            "切换摇一摇状态" -> {
                cameraStatus = !cameraStatus
                PbManager.setShakeCameraStatus(cameraStatus) {
                    logInfo("switchShakeState: $it")
                }
            }

            "监听摇一摇" -> {
                PbManager.addShakeCameraListener {
                    logInfo("shakeCamera: $it")
                }
            }

            "发送普通消息" -> {
                val watchNotifyData = WatchNotifyData(
                    "测试消息",
                    "这是一条测试消息",
                    1
                )
                PbManager.sendNotification(
                    Gson().toJson(watchNotifyData)
                )
            }

            "发送来电消息" -> {
                val watchNotifyData = WatchNotifyData(
                    "张三",
                    "1880992211",
                    3
                )
                PbManager.sendNotification(
                    Gson().toJson(watchNotifyData)
                )
            }

            "接挂电话监听" -> {
                PbManager.addCallStatusListener {
                    val resp = Gson().fromJson<BaseResponse<Boolean>>(it, BaseResponse::class.java)
                    logInfo("callStatus: ${resp.data}")
                }
            }

            "清空来电通知" -> {
                PbManager.clearCallStatus()
            }
            "监听找手机" -> {
                PbManager.addFindPhoneListener {
                    logInfo("findPhone: $it")
                }
            }
            "监听打开拍照" -> {
                PbManager.addShakeCameraOpenListener {
                    logInfo("openCamera: $it")
                }
            }
            "设置闹钟" -> {
                val param = BandAlarmData(
                    8,
                    30,
                    true
                )
                PbManager.setBandAlarm(Gson().toJson(param)) {
                    logInfo("setAlarm: $it")
                }
            }
            "设置心率参数" -> {
                val param = BandHeartSettingData(
                    30,
                    true,
                    false,
                    50,
                    160
                )
                PbManager.setBandHeartRateSetting(Gson().toJson(param)) {
                    logInfo("setHeartRateConfig: $it")
                }
            }
            "是否初始化" -> {
                logInfo("是否初始化: ${PbManager.isSdkInitialized}")
            }
            "是否连接中" -> {
                logInfo("是否连接中: ${PbManager.isDeviceConnected}")
            }
            "断开链接" -> {
                PbManager.disconnect {
                    logInfo("断开链接: $it")
                }
            }
            "恢复出厂" -> {
                PbManager.resetBand {
                    logInfo("恢复出厂: $it")
                }
            }
            else -> {}

        }
    }

    private fun getBasicConfig() {
        PbManager.getBasicConfig {
            themeFileName = if (PbManager.isJLieWatch) {
                "$filesDir/test/watch6.bin"
            } else {
                "$filesDir/test/rabbit_360.bin"
            }
            logInfo("getBasicConfig: $it")
        }
    }

    private fun getSupportedFeatures() {
        PbManager.getSupportedFeatures {
            logInfo("getSupportedFeatures: $it")
        }
    }

    private fun getUserInfo() {
        PbManager.getUserInfo {
            logInfo("getUserInfo: $it")
        }
    }


    private fun logTime(): String {
        return fullFmt.format(Date())
    }

    @SuppressLint("SetTextI18n")
    private fun logInfo(str: String) {
        runOnUiThread {
            val timeStr = logTime()
            binding.logView.apply {
                append("$timeStr $str \n")
                val offset = lineCount * lineHeight
                if (offset > height) {
                    scrollTo(0, offset - height - 20)
                }
            }
        }
    }

    private fun showInfoDialog(title: String, message: String, callback:()-> Unit) {
        AlertDialog.Builder(this)
            .setTitle(title)
            .setMessage(message)
            .setPositiveButton("好的") { dialog, _ ->
                callback()
            }.setCancelable(true)
            .show()
    }


    private fun showLoadingDialog() {
        if (!alertDialog.isShowing) {
            alertDialog.show()
        }
    }

    private fun dismissLoadingDialog() {
        if (alertDialog.isShowing) {
            alertDialog.dismiss()
        }
    }


    private fun testThemeFeature() {
        if (themeFileName.isEmpty()) {
            binding.themeLog.text = "请先获取基础配置"
            return
        }
        if (!File(themeFileName).exists()) {
            binding.themeLog.text = "表盘文件不存在"
            return
        }
        PbManager.addNewWatchTheme(themeFileName, progress = { progress ->
            binding.themeLog.text = "进度：$progress"
        }, callback = {
            binding.themeLog.text = "结果：$it"
        })
    }

    private fun testCustomBgFeature() {
        val filePath = "$filesDir/test/screen_360_2.png"
        if (!File(filePath).exists()) {
            binding.themeLog.text = "背景文件不存在"
            return
        }
        val customThemeData = CustomThemeData(
            filePath,
            0,
            0,
            0,
            4
        )
        PbManager.addWatchBackground(Gson().toJson(customThemeData), progress = { progress ->
            binding.themeLog.text = "进度：$progress"
        }, callback = {
            binding.themeLog.text = "结果：$it"
        })
    }

    private val filePickerLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            result.data?.data?.let { uri ->
                // Handle the selected file URI here
                handleSelectedFile(uri)
            }
        }
    }

    private fun openFilePicker() {
        val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
            addCategory(Intent.CATEGORY_OPENABLE)
            type = "*/*"  // For all file types
        }

        filePickerLauncher.launch(intent)
    }

    private fun handleSelectedFile(uri: Uri) {
        // Here you can work with the selected file URI
        // For example:
        val fileName = getFileName(uri)
        val fileSize = getFileSize(uri)
        MainScope().launch {
            otaFileP = uriToFile(this@TestingActivity, uri)
            binding.themeLog.text = "选择的文件: $fileName, 大小: $fileSize bytes"
        }
    }

    private fun getFileName(uri: Uri): String {
        var name = ""
        val cursor = contentResolver.query(uri, null, null, null, null)
        cursor?.use {
            if (it.moveToFirst()) {
                val displayNameIndex = it.getColumnIndex(OpenableColumns.DISPLAY_NAME)
                if (displayNameIndex != -1) {
                    name = it.getString(displayNameIndex)
                }
            }
        }
        return name
    }

    private fun getFileSize(uri: Uri): Long {
        var size = 0L
        val cursor = contentResolver.query(uri, null, null, null, null)
        cursor?.use {
            if (it.moveToFirst()) {
                val sizeIndex = it.getColumnIndex(OpenableColumns.SIZE)
                if (sizeIndex != -1 && !it.isNull(sizeIndex)) {
                    size = it.getLong(sizeIndex)
                }
            }
        }
        return size
    }


    suspend fun uriToFile(context: Context, uri: Uri): String {
        val contentResolver = context.contentResolver
        val tempFile = File.createTempFile("temp_", "ufw", context.cacheDir)
        contentResolver.openInputStream(uri)?.use { inputStream ->
            tempFile.outputStream().use { outputStream ->
                inputStream.copyTo(outputStream)
            }
        }

        return tempFile.path
    }

    private fun testOtaFeature(){
        if (otaFileP.isEmpty()) {
            binding.themeLog.text = "请先选择OTA文件"
            return
        }
        if (!File(otaFileP).exists()) {
            binding.themeLog.text = "文件不存在"
            return
        }
        PbManager.startOta(otaFileP, callback = { ret, p, msg ->

            if (ret == 0) {
                val alertDialog = AlertDialog.Builder(this)
                    .setTitle("OTA升级")
                    .setMessage("升级成功")
                    .setPositiveButton("好的") { dialog, _ ->
                        dialog.dismiss()
                        finish()
                    }
                    .create()
                alertDialog.show()
            } else {
                binding.themeLog.text = "结果类型 ====> $ret, 进度 ===>$p, 消息 ===> $msg"
            }
        })
    }
}